
// 
function getElementsByTagName(ele, tag)
{
	return ele.ownerDocument.evaluateXPath("descendant::" + tag, ele);
}

//
function getElementByTagName(ele, tag)
{
	var elements = getElementsByTagName(ele, tag);
	return (elements && elements.length > 0) ? elements[0] : null;
}

//
function quoteXML(s)
{
	return s.replace(/[&<>'"]/g, function(c)
	{
		return "&" + {
			"&": "amp",
			"<": "lt",
			">": "gt",
			"'": "apos",
			'"': "quot"
		}[c] + ";"
	})
}

//
function cloneNode(dstDoc, srcDoc, srcNode)
{
	var srcChildren = srcDoc.evaluateXPath("descendant::*", srcNode);
	for (var i = 0; i < srcChildren.length; i++)
	{
		var srcChild = srcChildren[i];
		var dstChild = dstDoc.makeElementNamed(srcChild.tagName);

		if(srcChild.textContent)
		{
			dstChild.textContent = srcChild.textContent;
		}

		srcChild.cloneNode(true);
		
		//return;
		var attrs = srcDoc.evaluateXPath("attribute::*", srcChild);
		if (attrs && attrs.length)
		{
			for (var j = 0; j < attrs.length; j++)
			{
				var name = srcDoc.evaluateXPath("/@name", attrs[j]);

				loadError('name: ' + name + attrs[j].nodeName + attrs[j].nodeType);
				break;
				//newElement.setAttribute(attr, e.value);
			}
			
			//dstChild.attributes = srcChild.attributes;
			break;
		}

		cloneNode(dstDoc, srcDoc, srcChild);
		//if (srcChild.childNodes)

         /*if(options.attrs) {
                options.attrs.forEach(function(e, i, a) {
                    newElement.setAttribute(e.name, e.value);
                }, this);
            }

            if(options.children) {
                options.children.forEach(function(e,i,a) {
                    newElement.appendChild( this.createNode( e, doc ) );
                }, this)
            }

            return newElement;
        }*/
    }
}

//
swap = false;
function loadXML(body, head)
{
	var xml = '<?xml version="1.0" encoding="UTF-8"?><atv>' + (head ? ('<head>' + head + '</head>') : '') + '<body>' + body + '</body></atv>';
	var doc = atv.parseXML(xml);
	//var swap = false;	// TODO: Determine swap flag based on xml page or js-generated page
	if (swap)
	{
		atv.loadAndSwapXML(doc);
		return;
		//swap = false;
		var cur = getElementByTagName(doc.rootElement, 'scroller');
		var old = getElementByTagName(document.rootElement, 'scroller');
		var parent = getElementByTagName(document.rootElement, 'body');
		cloneNode(document, doc, cur);
		//parent.replaceChild(cur, old);
		//parent.appendChild(cur);
		//loadError('cur:' + cur + '\nold:' + old + '\nparent:' + parent);
		//document.rootElement.replaceChild(cur, old);
		return;
		//doc.rootElement;
		var divider = ATVUtils.createNode(
					{
						"name": "collectionDivider",
						"attrs": [
						{
							"name": "alignment",
							"value": "center"
						}, {
							"name": "accessibilityLabel",
							"value": "",
						}],
						"children": [
						{
							"name": "title",
							"text": "载入2...",
						}],
					});
		try
		{
			items.appendChild(divider2);
		}
		catch(e)
		{
			ATVUtils.loadError(e);
		}
		
	}
	else
	{
		atv.loadXML(doc);
	}
}

//
function loadError(message, description)
{
	loadXML('<dialog id="error"><title><![CDATA[' + (message || '') + ']]></title><description><![CDATA[' + (description || '') + ']]></description></dialog>');
}

//
function loadText(self, page, text)
{
	// 
	var phost = page.substring(0, page.indexOf('/', 8));
	var pbase = page.substring(0, page.lastIndexOf('/') + 1);
	var sbase = self.substring(0, self.lastIndexOf('/') + 1);

	// 
	var posters = '';
	var photos = '';
	var poster_count = 0;
	var photo_count = 0;
	if(text != null)
	{
		// Lookup lines
		var lines = text.split('</tr>');
		if(lines.length < 2) lines = text.split('</li>');
		if(lines.length < 2) lines = text.split('<br>');

		// Geenrate item
		for(var i = 0; i < lines.length; i++)
		{
			var re = new RegExp('<a href="(.*?)">(.*?)</a>', "i");
			var rs = re.exec(lines[i]);
			if(rs)
			{
				var href = rs[1];
				var name = rs[2];

				// Skip some special
				if(name.charAt(0) == '.') continue;
				if(href.indexOf('?') != -1) continue;
				if(name.indexOf('Parent Directory') >= 0) continue;

				// Make full href
				if(href.indexOf(':') == -1)
				{
					if(href.charAt(0) == '/') href = phost + href;
					else href = pbase + href;
				}
				href = quoteXML(href);

				// Determine type
				var type;
				if(href.charAt(href.length - 1) == '/')
				{
					type = 'dir';
				}
				else
				{
					type = href.substring(href.lastIndexOf('.') + 1).toLowerCase();

					// Make name without extsion
					var pos = name.lastIndexOf('.');
					if(pos != -1) name = name.substring(0, pos);
				}

				// Geenrate item
				if(type == 'dir' || type == 'mp4' || type == 'mov' || type == 'avi' || type == 'mpg' || type == 'm3u' || type == 'mp3')
				{
					var id = type + ++poster_count;
					var action = 'loadPage(\'' + self + '?' + href + '\')';
					var thumb = (pbase.indexOf('Pictures') != -1);	// TRICK: Thumbnail for special uri // TODO: From setting's cookie for sbase
					
					posters += '<sixteenByNinePoster alwaysShowTitles="true" id="' + id + '" onPlay="' + action + '" onSelect="' + action + '">';
					posters += '<title>' + quoteXML(name) + '</title>';
					posters += '<image>' + sbase + (thumb ? ('thumb/' + encodeURIComponent(name) + '.jpg') : ('image/' + type + '.png')) + '</image>';
					posters += '<defaultImage>resource://Poster.png</defaultImage>';
					posters += '</sixteenByNinePoster>';
				}
				else if(type == 'jpg' || type == 'png' || type == 'gif')
				{
					var id = type + ++photo_count;
					photos += '<photo id="' + id + '" onSelect="onPhotoSelection(\'' + id + '\')" onPlay="onSlideshowStart(\'' + id + '\')">';
					photos += '<assets><photoAsset width="486" height="720" src="' + href + '"/></assets>';
					photos += '</photo>';
				}
			}
		}
	}

	//
	if(photo_count == 0 && poster_count == 0)
	{
		loadError('没有内容', page);
		return;
	}

	// Geenrate XML
	var body;
	var head = '<script src="' + sbase + 'media.js"/>';
	if(photo_count > poster_count)
	{
		var purl = (page.charAt(page.length - 1) == '/') ? page.substring(0, page.length - 1) : page;
		var title = decodeURIComponent(purl.substring(purl.lastIndexOf('/') + 1));

		head += '<script src="' + sbase + 'slide.js"/>';
		body = '<mediaBrowser id="browser" gridLayout="mixed">';
		body += '<header><headerWithCountAndButtons><title>' + title + '</title><count>' + photo_count + '</count>';
		body += '<buttons><actionButton id="slideshow" onSelect="onSettingsSelection()" onPlay="onSlideshowStart()"><title>幻灯片播放</title></actionButton></buttons>';
		body += '</headerWithCountAndButtons></header><items>' + photos + '</items></mediaBrowser>';
	}
	else
	{
		body = '<scroller id="scroller"><items><grid columnCount="5" id="grid"><items>' + posters + '</items></grid></items></scroller>';
	}

	loadXML(body, head);
}

//
function loadPage(url)
{
	var page;
	var self;
	var search = url.indexOf('?');
	if(search != -1)
	{
		self = url.substring(0, search);
		page = url.substring(search + 1);
	}
	else
	{
		//page = url.substring(0, url.lastIndexOf('/') + 1);	// Use self dir url as default
		page = url.substring(0, url.indexOf('/', 8) + 1);	// Use self root url as default
		//page = 'http://router/media/DATA/';	// Use router url as default, for local file test only
		//page = 'http://hdweb.googlecode.com/svn/trunk/Folders.htm';
		self = url;
	}
	
	// Load player
	var type = page.substring(page.lastIndexOf('.') + 1).toLowerCase();
	if(type == 'mp4' || type == 'mov' || type == 'avi' || type == 'mpg' || type == 'm3u' || type == 'mp3')
	{
		loadXML('<videoPlayer id="player"><httpFileVideoAsset id="asset"><mediaURL>' + page + '</mediaURL></httpFileVideoAsset></videoPlayer>');
		return;
	}

	// Request page
	var req = new XMLHttpRequest();
	req.onreadystatechange = function()
	{
		try
		{
			if(req.readyState == 4)
			{
				if(req.status == 200)
				{
					loadText(self, page, req.responseText);
				}
				else
				{
					loadError('状态错误：' + req.status, page);
				}
			}
		}
		catch(e)
		{
			req.abort();
			loadError(e, page);
		}
	}
	req.open('GET', page, true);
	req.send();
}

//
atv.onPageLoad = function(id)
{
	if(id == 'media')
	{
		try
		{
			swap = true;
			//loadError('OBJ: ' + document.title);
			loadPage('http://router/appletv/media.xml?http://router/media/TEMP/media/');//document.documentURI);
		}
		catch(e)
		{
			loadError(e);
		}
	}
};
